package com.urban.pooling.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.urban.pooling.domain.GeoPoint;
import com.urban.pooling.domain.Route;
import com.urban.pooling.repository.GeoPointRepository;

public class WaypointFinder implements Runnable {
	private static final Logger LOG = LoggerFactory.getLogger(WaypointFinder.class);

	public GeoPointRepository geoPointRepo;
	public Route route;

	public WaypointFinder(GeoPointRepository geoPointRepo, Route route) {
		super();
		this.geoPointRepo = geoPointRepo;
		this.route = route;
	}

	@Override
	public void run() {
		List<GeoPoint> waypoints = getWaypoints(route);
		geoPointRepo.delete(route.getStartPoint());
		geoPointRepo.delete(route.getDestPoint());
		geoPointRepo.save(waypoints);
	}

	/**
	 * Requests the waypoints from Google Directions Api
	 * 
	 * @param route
	 */
	private List<GeoPoint> getWaypoints(Route route) {
		GoogleMapsService googleMapsService = new GoogleMapsService();
		List<GeoPoint> waypoints = googleMapsService.getRouteWaypoints(route.getStartPoint(), route.getDestPoint());
		List<GeoPoint> waypointsToSave = new ArrayList<GeoPoint>();
		LOG.debug("Waypoints from google service, size:" + waypoints.size() + ",points:" + waypoints.toString());
		int k = 0;
		for (int i = 0; i < waypoints.size(); i++) {
			if (i % 10 == 0 || i == waypoints.size() - 1) {
				waypoints.get(i).setOrder(k);
				waypoints.get(i).setRoute(route);
				waypointsToSave.add(waypoints.get(i));
				k++;
			}
		}
		LOG.debug("Returning waypoints, size:" + waypointsToSave.size() + ",points:" + waypointsToSave.toString());
		return waypointsToSave;
	}

}
